﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;

using Core.Model.Column;
using Core.Model.Hierarchy;
using Core.Shared.Monads;

namespace Core.Logic
{
	public class PdfExportManager
	{
		#region Private fields

		private string _fontFamily = "Calibry";

		#endregion

		#region Public methods

		public void Export(Research research, string filePath)
		{
			using (var fileStream = new FileStream(filePath, FileMode.OpenOrCreate))
			{
                var document = new Document(PageSize.A4, 10, 10, 90, 10);
					// create a writer that listens to the document
					PdfWriter.GetInstance(document, fileStream);

					//set some header stuff
					document.AddTitle(String.Format("Research on {0}", research.Date));

					document.Open();

					// add content to the document
					CreatePages(research, document);

					document.Close();	
			}
		}

		public void SetFont(string fontFamily)
		{
			_fontFamily = fontFamily;
		}

        #endregion

		#region Private methods

		private void CreatePages(Research research, Document document)
		{
			document.NewPage();

			//to initiate empty table with one column
			int columnsCount = !research.Columns.Any() ? 1 : research.Columns.Count();

			var pdfTable = new PdfPTable(columnsCount);
			pdfTable.DefaultCell.Padding = 3;
			pdfTable.WidthPercentage = 100;
			pdfTable.DefaultCell.BorderWidth = 1;
			pdfTable.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;

			if (!research.Columns.Any())
			{
				pdfTable.HeaderRows = 0;
				pdfTable.AddCell(FormatPhrase(" "));
			}
			else
			{
				foreach (ExaminationColumn column in research.Columns)
				{
					pdfTable.AddCell(FormatHeaderPhrase(column.Name));
				}

				pdfTable.HeaderRows = 1;
				pdfTable.DefaultCell.BorderWidth = 1;

				List<ExaminationColumn> columns = research.Columns.ToList();
				if (research.Cases.Count == 0)
				{
					for (int i = 0; i < columnsCount; i++)
					{
						pdfTable.AddCell(FormatPhrase(" "));
					}
				}
				else
				{
					foreach (ExpandoObject row in research.Cases)
					{
						foreach (var column in columns)
						{
							var cell = row.FirstOrDefault(c => c.Key == column.Name);
							pdfTable.AddCell(FormatPhrase(cell.Value.Return(c => c.ToString(), String.Empty)));
						}
					}
				}
			}

			document.Add(pdfTable);
		}

		private Phrase FormatHeaderPhrase(string value)
		{
			return new Phrase(value, FontFactory.GetFont(_fontFamily, 8, Font.NORMAL, BaseColor.BLACK));
		}

		private Phrase FormatPhrase(string value)
		{
			return new Phrase(value, FontFactory.GetFont(_fontFamily, 8));
		}

		#endregion
	}
}